package com.dh.order.message;

import java.util.List;

import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dh.order.service.IRedisService;
import com.dh.order.utils.JsonUtil;
import com.dh.product.common.ProductInfoOutput;
import com.fasterxml.jackson.core.type.TypeReference;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 作者 dinghao
 * @version 创建时间：2018年11月19日 下午12:39:04
 * @Description 类说明 :
 */
@Component
@Slf4j
public class ProductReceiver {

	private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";

	@Autowired
	private IRedisService iRedisService;

	@RabbitListener(queuesToDeclare = @Queue("productInfo"))
	public void process(String message) throws Exception {
		// message => ProductInfoOutput
		// List<ProductInfoOutput> productInfoOutputList =
		// JacksonUtil.json2list(message, ProductInfoOutput.class);
		@SuppressWarnings("unchecked")
		List<ProductInfoOutput> productInfoOutputList = (List<ProductInfoOutput>) JsonUtil.fromJson(message,
				new TypeReference<List<ProductInfoOutput>>() {
				});
		log.info("从对列中获取{}", productInfoOutputList);

		// 存储到redis
		for (ProductInfoOutput productInfoOutput : productInfoOutputList) {
			iRedisService.set(String.format(PRODUCT_STOCK_TEMPLATE, productInfoOutput.getProductId()),
					String.valueOf(productInfoOutput.getProductStock()));
		}
	}

}
